package com.cc.demo.controller;

import com.cc.demo.channel.TransactionChannelConstant;
import com.cc.demo.dto.TransactionMessage;
import com.cc.demo.entity.Order;
import com.cc.demo.message.TransactionMessagePublishAdapter;
import com.cc.demo.message.TransactionMessagePublisher;
import com.cc.demo.service.OrderService;
import com.cc.demo.utils.UuidGenerator;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;
    private final TransactionMessagePublisher publisher;


    @Value("${spring.application.name}")
    private String owner;


    @GetMapping("/create")
    public String createOrder() {
        Order order = new Order();
        TransactionMessage<Object> transactionMessage = TransactionMessage.builder()
                .channel(TransactionChannelConstant.CONSUMER_OUTPUT)
                .body(order)
                .domain(Order.class.getName())
                .owner(owner)
                .businessKey(UuidGenerator.newUuid()).build();
        publisher.sendSyncTransactionMessage(transactionMessage, new TransactionMessagePublishAdapter() {
            @Override
            public void afterPreCommitMessage(TransactionMessage<?> transactionMessage) {
                orderService.createOrder(order);
            }
        });
        return "success";
    }


    @GetMapping("/check/status/{id}")
    public boolean checkOrderStatus(@PathVariable("id") Integer id) {
        return orderService.checkOrderStatus(id);
    }
}
